<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="filters">
                <el-form-item>
                    <el-input v-model="filters.name" placeholder="名字"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="success" @click="queryPage">
                        <i class="el-icon-search"></i>
                        查询
                    </el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleAdd">
                        <i class="el-icon-plus"></i>
                        新增</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="success" @click="onoff(1)">
                        <i class="el-icon-sell"></i>
                        服务上线</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="danger" @click="onoff(0)">
                        <i class="el-icon-sold-out"></i>
                        服务下线</el-button>
                </el-form-item>
            </el-form>
        </el-col>

        <!--列表-->
        <!--		:data :绑定的数据-->
        <!--		v-loading: 页面css样式等东西加载之后加载加载数据-->
        <!--		prop:对应的是:data绑定的对象的属性-->
        <!--		label :描述-->
        <el-table :data="dept" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
                  style="width: 100%;">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column type="index" width="60">
            </el-table-column>
            <el-table-column prop="name" label="名字"  sortable>
            </el-table-column>
            <el-table-column prop="saleprice" label="售价"  sortable>
            </el-table-column>
            <el-table-column prop="costprice" label="成本价"  sortable>
            </el-table-column>
            <el-table-column prop="salecount" label="销量"  sortable>
            </el-table-column>
            <el-table-column prop="state" label="状态" :formatter="formatSex" sortable>
            </el-table-column>
            <el-table-column prop="onsaletime" label="上架时间"  sortable>
            </el-table-column>

            <el-table-column label="操作" width="150">
                <template slot-scope="scope">
                    <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--分页条-->
        <el-col :span="24" class="toolbar">
            <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
            <!--			current-change:自带的事件,我当前页发生改变时,就会触发此事件-->
            <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="5"
                           :total="total" style="float:right;">
            </el-pagination>
        </el-col>


        <!--新增界面-->
        <el-dialog title="新增" :visible.sync="addFormVisible" :close-on-click-modal="false">
            <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
                <el-form-item label="名字" prop="name">
                    <el-input v-model="addForm.name" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="相册" prop="name">
                    <el-upload
                            class="avatar-uploader"
                            :action="fileRequestUrl"
                            :show-file-list="false"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload">
                        <img v-if="addForm.resources"  :src="addForm.resources" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="售价" prop="name">
                    <el-input v-model="addForm.saleprice" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="成本" prop="name">
                    <el-input v-model="addForm.costprice" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="服务备注" prop="name">
                    <el-input v-model="addForm.orderNotice" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="服务详情" prop="name">
                    <div class="edit_container">
                        <quill-editor
                                v-model="addForm.intro"
                                ref="myQuillEditor"
                                class="editer"
                                :options="editorOption"
                                @ready="onEditorReady($event)">
                        </quill-editor>
                    </div>
                </el-form-item>

                <!--				<el-form-item label="部门编号" prop="sn">-->
                <!--					<el-input v-model="addForm.sn" auto-complete="off"></el-input>-->
                <!--				</el-form-item>-->
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click.native="addFormVisible = false">取消</el-button>
                <el-button type="primary" @click.native="save" :loading="addLoading">提交</el-button>
            </div>
        </el-dialog>
    </section>
</template>

<script>

    //import util from '../../common/js/util'
    //import NProgress from 'nprogress'
    //import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

    import {quillEditor} from "vue-quill-editor"; //调用编辑器
    import "quill/dist/quill.core.css"
    import "quill/dist/quill.snow.css"
    import "quill/dist/quill.bubble.css"

    // 工具栏配置
    const toolbarOptions = [
        ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
        ["blockquote", "code-block"], // 引用  代码块-----['blockquote', 'code-block']
        [{header: 1}, {header: 2}], // 1、2 级标题-----[{ header: 1 }, { header: 2 }]
        [{list: "ordered"}, {list: "bullet"}], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
        [{script: "sub"}, {script: "super"}], // 上标/下标-----[{ script: 'sub' }, { script: 'super' }]
        [{indent: "-1"}, {indent: "+1"}], // 缩进-----[{ indent: '-1' }, { indent: '+1' }]
        [{direction: "rtl"}], // 文本方向-----[{'direction': 'rtl'}]
        [{size: ["small", false, "large", "huge"]}], // 字体大小-----[{ size: ['small', false, 'large', 'huge'] }]
        [{header: [1, 2, 3, 4, 5, 6, false]}], // 标题-----[{ header: [1, 2, 3, 4, 5, 6, false] }]
        [{color: []}, {background: []}], // 字体颜色、字体背景颜色-----[{ color: [] }, { background: [] }]
        [{font: []}], // 字体种类-----[{ font: [] }]
        [{align: []}], // 对齐方式-----[{ align: [] }]
        ["clean"], // 清除文本格式-----['clean']
        ["image", "link", "video"] // 链接、图片、视频-----['link', 'image', 'video']
    ];
    export default {
        components: {
            //使用编辑器
            quillEditor
        },
        computed:{
            fileRequestUrl() {
                return this.$http.defaults.baseURL + "/file/upload"
            }
        },
        data() {
            return {
                editorOption: {
                    modules: {
                        //工具栏定义的
                        toolbar: toolbarOptions
                    },
                    //主题
                    theme: "snow",
                    placeholder: "请开始书写您的博客内容..."
                },
                filters: {
                    name: '',
                    managerId: '',
                    parentId: ''
                },
                dept: [],
                total: 0,
                page: 1,
                listLoading: false,
                sels: [],//列表选中列
                managerList: [],
                editFormVisible: false,//编辑界面是否显示
                editLoading: false,
                editFormRules: {
                    name: [
                        {required: true, message: '请输入部门名称', trigger: 'blur'}
                    ]
                },
                //编辑界面数据
                editForm: {
                    id: '',
                    name: '',
                    sn: ''
                },

                addFormVisible: false,//新增界面是否显示
                addLoading: false,
                addFormRules: {
                    name: [
                        {required: true, message: '请输入姓名', trigger: 'blur'}
                    ]
                },
                //新增界面数据
                addForm: {
                    resources:''
                },
                superDeptList: [],
                parentList: [],
            }
        },
        methods: {
            onoff(v){
                var ids = this.sels.map(item => item.id);
                let param = {
                    id:ids[0],
                    state:v
                };
                this.$http.post(`/product/onoff?id=${ids}&state=${v}`).then(res=>{
                    this.$message.success(res.data.message);
                    this.queryPage();
                })
            },
            //图片文件上传成功事件
            handleAvatarSuccess(res, file) {
                if (res.success) {
                    this.addForm.resources = res.data;
                    console.log(this.addForm.resources)
                } else {
                    this.$message.error(res.message);
                }
            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            onEditorReady(editor) {
                //当富文本编辑框初始化好执行
                console.log('富文本编辑框初始化---------完成');
            },
            //性别显示转换
            //row 当前行row = user  column当前列
            formatSex: function (row, column) {
                return row.state == 0 ? '已下线' : '已上线';
            },
            handleCurrentChange(val) {
                //var 就是当前页的数据
                this.page = val;
                this.queryPage();
            },
            //获取部门列表
            queryPage() {
                //封装的数据
                let para = {
                    //page 就是当前页
                    pageIndex: this.page,
                    //这个是高级查询的条件
                    keyword: this.filters.name,
                };
                this.listLoading = true;
                //NProgress.start();
                this.$http.get(`/product/queryPage`, {params: para}).then((res) => {
                    // console.log("后端发送过来的分页数据:"+JSON.stringify(res));
                    //
                    this.total = res.data.data.total;
                    //
                    this.dept = res.data.data.list;
                    //关闭进度条
                    this.listLoading = false;
                    //NProgress.done();
                });
            },
            //删除
            handleDel: function (index, row) {
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    //NProgress.start();
                    let para = {id: row.id};
                    this.$http.delete('/product/' + row.id).then((res) => {
                        this.listLoading = false;
                        //NProgress.done();
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        this.queryPage();
                    });
                }).catch(() => {

                });
            },
            //显示编辑界面
            handleEdit: function (index, row) {
                //显示编辑页面的模态框
                this.addFormVisible = true;
                //Object.assign 是拷贝对象 BeanUtil.copyof()
                // console.log(!!row.state);
                this.addForm = row;
                // this.addForm.state = Boolean(row.state);
                // let ids = row.dirPath.split('/').filter(m => m.trim() != '').map(Number).slice(0, -1);
                // this.addForm.parentIds = ids;
                // console.log(this.addForm.state)
                //console.log("当前修改的数据是:" + JSON.stringify(this.addForm))
            },
            //显示新增界面
            handleAdd: function () {
                this.addFormVisible = true;
                this.addForm = {};
            },
            //编辑
            save: function () {
                 this.$refs.addForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            //这里面是获取数据的
                            this.editLoading = true;
                            //拷贝对象
                            let para = Object.assign({}, this.addForm);

                            this.$http.post("/product/save", para).then((res) => {
                                this.editLoading = false;
                                //NProgress.done();
                                this.$message({
                                    message: res.data.message,
                                    type: 'success'
                                });
                                this.$refs['editForm'].resetFields();
                                this.editFormVisible = false;
                                this.queryPage();
                            });
                        });
                    }
                });
            },
            //新增
            addSubmit: function () {
                //$refs调用js 原生dom元素
                //validate
                this.$refs.addForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            //这里才是我们处理数据的地方
                            this.addLoading = true;

                            this.addForm.state = this.addForm.state & 1;
                            let para = Object.assign({}, this.addForm);

                            this.$http.post("/department", para).then((res) => {
                                this.addLoading = false;
                                //elementUi的提示弹框
                                this.$message({
                                    message: res.data.message,
                                    type: res.data.success ? 'success' : 'error'
                                });
                                //重新set数据
                                this.$refs['addForm'].resetFields();
                                this.addFormVisible = false;
                                this.queryPage();
                                this.parentList();
                                this.superDeptList();
                            });
                        });
                    }
                });
            },
            //复选勾选框的方法
            selsChange: function (sels) {
                this.sels = sels;
            },
            //批量删除
            batchRemove: function () {
                var ids = this.sels.map(item => item.id);
                this.$confirm('确认删除选中记录吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    //NProgress.start();
                    // let para = {ids: ids};
                    this.$http.delete('/product', {data: ids}).then((res) => {
                        this.listLoading = false;
                        //NProgress.done();
                        this.$message({
                            message: res.data.message,
                            type: 'success'
                        });
                        this.queryPage();
                    });
                }).catch(() => {

                });
            },
            getemp() {
                this.$http.get('/employee').then(res => {
                    this.managerList = res.data.data;
                })
            },
            getSuperDept() {
                this.$http.get('/department/superDept').then(res => {
                    this.superDeptList = res.data.data;
                })
            },
            //获取上级部门
            getParentList() {
                this.$http.get('/department/parentList').then(res => {
                    this.parentList = res.data.data;
                })
            },
        },
        //就是页面已加载完成就会去触发这个mounted
        mounted() {
             this.queryPage();
            // this.getemp();
            // this.getSuperDept();
            // this.getParentList();
        }
    }

</script>

<style scoped>
    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>
